from django import forms
from django.core.exceptions import ValidationError
from web.forms.widgets import ColorRadioSelect
from web.forms.bootstrap import BootstrapForm
from web import models


class ProjectModelForm(BootstrapForm, forms.ModelForm):
    bootstarp_class_exclude = ['color']
    desc = forms.CharField(label='项目描述', widget=forms.Textarea({'height': '300px', 'class': 'test'}))

    class Meta:
        model = models.Project
        fields = ['name', 'color', 'desc']
        widgets = {
            'color': ColorRadioSelect(attrs={'class': 'color-radio'})
        }

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['desc'].widget.attrs.update({'style': 'height:300px'})
        self.request = request

    def clean_name(self):
        # 项目名
        name = self.cleaned_data['name']
        user = self.request.tracer.user
        exist = models.Project.objects.filter(name=name, creator=user).exists()
        if exist:
            raise ValidationError("项目已存在，请勿重复创建")

        # 当前是否还有额度
        # 现在已创建的多少项目
        count = models.Project.objects.filter(creator=self.request.tracer.user).count()
        if count >= self.request.tracer.price_policy.numb:
            raise ValidationError('创建的项目数已超出最大数量，请购买套餐')
        return name
